
package org.example.exception;

import org.apache.commons.lang3.StringUtils;
import org.example.result.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.stream.Collectors;

/**
 * 全局异常捕获类
 */
@RestControllerAdvice()
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = AbstractException.class)
    public ResultInfo abstractExceptionHandle(HttpServletRequest request, AbstractException ex) {
        logger.error("========================================== ServerException-Start ==========================================");
        String params = getRequestParams(request);
        logger.error("RequestURL     : {}", request.getRequestURL());
        logger.error("HTTP Method    : {}", request.getMethod());
        logger.error("Params         : {}", params);
        logger.error("IP             : {}", request.getRemoteAddr());
        logger.error("Cause          : ", ex);
        logger.error("ExMessage      : {}", ex.getMessage());
        logger.info("=========================================== ServerException-End ===========================================");
        return ResultInfo.error(ex.getMessage());
    }

    private String getRequestParams(HttpServletRequest request) {
        if (HttpMethod.POST.name().equalsIgnoreCase(request.getMethod()) && StringUtils.startsWithIgnoreCase(MediaType.APPLICATION_JSON_VALUE, request.getContentType())) {
            return getJsonPostBody(request);
        } else {
            return request.getParameterMap().entrySet().stream()
                    .map(entry -> entry.getKey() + "=" + String.join(",", entry.getValue()))
                    .collect(Collectors.joining(", "));
        }
    }

    private String getJsonPostBody(HttpServletRequest request) {
        StringBuilder jsonBody = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBody.append(line);
            }
        } catch (IOException e) {
            logger.error("Error reading the request body", e);
        }
        return jsonBody.toString();
    }

}